<?php


namespace app\admin\controller\system;


use app\admin\controller\BaseController;
use app\common\exception\MessageException;
use app\common\model\mysql\system\DictData as DictDataModel;
use app\common\validate\DictValidate;
use app\common\validate\IDMustBePositiveInt;

class DictData extends BaseController
{
    public function list()
    {
        // 分页查询
        try {
            $params = $this->request->param();
            $result = DictDataModel::list($params);

            return $this->renderSuccess($result);
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    /**
     * 新建
     * @return \think\response\Json|void
     * @throws MessageException
     * @throws \app\common\exception\ParameterException
     */
    public function create()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不合法']);
        }
        (new DictValidate())->goCheck();
        $data = $this->request->param();
        try {
            $findData = DictDataModel::checkCode($data['code']);

            if ($findData) {
                return $this->renderFail('编码已存在');
            }

            DictDataModel::add($data);
            return $this->renderSuccess([], '添加成功');
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function update()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不合法']);
        }
        (new DictValidate())->goCheck();
        $data = $this->request->param();

        try {
            $findData = DictDataModel::checkCode($data['code'], $data['id']);

            if ($findData) {
                return $this->renderFail('编码已存在');
            }

            DictDataModel::add($data);
            $this->renderSuccess([], '添加成功');
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function delete()
    {
        (new IDMustBePositiveInt())->goCheck();
//        if (!is_array($delIds)) {
//            throw new MessageException(['msg' => '参数不合法']);
//        }
        try {
            $findData = DictDataModel::where('id', $params['id'])->find();

            if (!$findData) {
                return $this->renderFail('字典不存在');
            }
            // 删除
            DictDataModel::remove($params);
            return $this->renderSuccess([], '删除成功');
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }
}